package view.conponent;

import com.alibaba.fastjson.JSON;
import model.user.Staff;
import net.ToServer;
import net.passClass.PassStaff;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StaffManager extends Box {
    final int WIDTH = 1080;

    private final JTable table;
    private final Vector<Vector<String>> tableData;
    private final DefaultTableModel tableModel;

    public StaffManager(int title) {
        //指定垂直布局
        super(BoxLayout.Y_AXIS);

        //组装表格
        String[] ts = {"登陆名","姓名","生日","专长","电话","身份证号","UID"};
        Vector<String> titles = new Vector<>(Arrays.asList(ts));

        tableData = new Vector<>();

        tableModel = new DefaultTableModel(tableData, titles);
        table = new JTable(tableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane);

        JPanel textFieldPanel = new JPanel();
        textFieldPanel.setMaximumSize(new Dimension(WIDTH, 80));
        textFieldPanel.setMinimumSize(new Dimension(870, 80));
        textFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        Box box1 = Box.createVerticalBox();
        JTextField username = new JTextField(8);
        JLabel usernameStr = new  JLabel("登陆名");
        box1.add(usernameStr);
        box1.add(username);


        Box box2 = Box.createVerticalBox();
        JTextField name = new JTextField(8);
        JLabel nameStr = new  JLabel("姓名");
        box2.add(nameStr);
        box2.add(name);

        Box box3 = Box.createVerticalBox();
        JTextField birthday = new JTextField(8);
        JLabel birthdayStr = new  JLabel("生日");
        box3.add(birthdayStr);
        box3.add(birthday);

        Box box4 = Box.createVerticalBox();
        JTextField specialty = new JTextField(8);
        JLabel specialtyStr = new  JLabel("专长");
        box4.add(specialtyStr);
        box4.add(specialty);

        Box box5 = Box.createVerticalBox();
        JTextField tel = new JTextField(8);
        JLabel telStr = new  JLabel("电话");
        box5.add(telStr);
        box5.add(tel);

        Box box6 = Box.createVerticalBox();
        JTextField idNumber = new JTextField(8);
        JLabel idNumberStr = new  JLabel("身份证号");
        box6.add(idNumberStr);
        box6.add(idNumber);

        Box box7 = Box.createVerticalBox();
        JTextField uid = new JTextField(8);
        JLabel uidStr = new  JLabel("UID");
        box7.add(uidStr);
        box7.add(uid);

        Box box8 = Box.createVerticalBox();
        JTextField password = new JTextField(8);
        JLabel passwordStr = new  JLabel("密码");
        box8.add(passwordStr);
        box8.add(password);


        textFieldPanel.add(box1);
        textFieldPanel.add(box2);
        textFieldPanel.add(box3);
        textFieldPanel.add(box4);
        textFieldPanel.add(box5);
        textFieldPanel.add(box6);
        textFieldPanel.add(box7);
        textFieldPanel.add(box8);
        this.add(textFieldPanel);

        JPanel btnPanel = new JPanel();
        btnPanel.setMaximumSize(new Dimension(WIDTH, 80));
        btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        JButton addBtn = new JButton("添加");
        JButton deleteBtn = new JButton("删除");
        JButton updateBtn = new JButton("修改");
        JButton getBtn = new JButton("查找");
        JButton refreshBtn = new JButton("刷新");

        addBtn.addActionListener(e -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
            long time = 0;
            try {
                String str = birthday.getText();
                String pattern = "^\\d{4}-\\d{1,2}-\\d{1,2}";

                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(str);
                if (m.matches()) {
                    time = dateFormat.parse(str).getTime();
                }
                ToServer.receive("/user/staff/add","username:"+username.getText()+"\n" +
                        "name:" +name.getText()+"\n" +
                        "birthday:" +time+"\n" +
                        "specialty:" +specialty.getText()+"\n" +
                        "tel:" +tel.getText()+"\n" +
                        "idNumber:" +idNumber.getText()+"\n" +
                        "title:" + title + "\n" +
                        "password:" + password.getText() + "\n" +
                        "uid:" +uid.getText());
                requestData(title);
            } catch (ParseException parseException) {
                JOptionPane.showMessageDialog(textFieldPanel, "信息格式错误");
            }
        });

        deleteBtn.addActionListener(e -> {
            int[] selected = table.getSelectedRows();
            for (int num: selected) {
                System.out.println(num);
                ToServer.receive("/user/staff/delete","uid:"+table.getValueAt(num,6));
            }
            requestData(title);
        });

        updateBtn.addActionListener(e -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
            long time = 0;
            try {
                String str = birthday.getText();
                String pattern = "^\\d{4}-\\d{1,2}-\\d{1,2}";

                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(str);
                if (m.matches()) {
                    time = dateFormat.parse(str).getTime();
                }
            } catch (ParseException parseException) {
                JOptionPane.showMessageDialog(textFieldPanel, "信息格式错误");
            }

            int selected = table.getSelectedRow();
            ToServer.receive("/user/staff/update",
                    "username:" + username.getText() + "\n" +
                            "uid:" + table.getValueAt(selected, 6) + "\n" +
                            "name:" + name.getText() + "\n" +
                            "birthday:" + time + "\n" +
                            "specialty:" + specialty.getText() + "\n" +
                            "tel:" + tel.getText() + "\n" +
                            "idNumber:" + idNumber.getText() + "\n" +
                            "title:" + title + "\n" +
                            "uid:" + uid.getText());
            requestData(title);
        });

        getBtn.addActionListener(e -> {
            long time = 0;
            try {
                String str = birthday.getText();
                String pattern = "^\\d{4}-\\d{1,2}-\\d{1,2}";

                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(str);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
                if (m.matches()) {
                    time = dateFormat.parse(birthday.getText()).getTime();
                }
            } catch (ParseException parseException) {
                JOptionPane.showMessageDialog(textFieldPanel, "信息格式错误");
            }
            PassStaff receive =(PassStaff) ToServer.receive("/user/staff/get",
                    "username:"+username.getText()+"\n" +
                            "name:" +name.getText()+"\n" +
                            "birthday:" +time+"\n" +
                            "specialty:" +specialty.getText()+"\n" +
                            "tel:" +tel.getText()+"\n" +
                            "idNumber:" +idNumber.getText()+"\n" +
                            "title:" + title + "\n" +
                            "uid:" +uid.getText());
            requestData(receive.getData());
        });

        table.getSelectionModel().addListSelectionListener(e -> {
            int row = table.getSelectedRow();
            if(row != -1) {
                username.setText(table.getValueAt(table.getSelectedRow(),0).toString());
                name.setText(table.getValueAt(table.getSelectedRow(),1).toString());
                birthday.setText(String.valueOf(table.getValueAt(table.getSelectedRow(),2)));
                specialty.setText(table.getValueAt(table.getSelectedRow(),3).toString());
                tel.setText(table.getValueAt(table.getSelectedRow(),4).toString());
                idNumber.setText(table.getValueAt(table.getSelectedRow(),5).toString());
                uid.setText(table.getValueAt(table.getSelectedRow(),6).toString());
            }
        });

        refreshBtn.addActionListener(e -> requestData(title));

        btnPanel.add(addBtn);
        btnPanel.add(deleteBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(getBtn);
        btnPanel.add(refreshBtn);
        this.add(btnPanel);

        requestData(title);

    }

    public void requestData(int title){
        ArrayList<Staff> data = ((PassStaff)ToServer.receive("/user/staff/get","title:"+title)).getData();
        requestData(data);

    }

    public void requestData(ArrayList<Staff> data){
        tableData.clear();
        for(int i = 0; i<data.size(); i++){
            Staff staff = JSON.parseObject(JSON.toJSONString(data.get(i)),Staff.class);
            System.out.println(staff);
            Vector<String> vector = new Vector<>();
            vector.add(staff.getUserName());
            vector.add(staff.getName());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
            vector.add(staff.getBirthday()==null?
                    null:
                    dateFormat.format(staff.getBirthday()));
            vector.add(staff.getSpecialty());
            vector.add(staff.getTel());
            vector.add(staff.getIdNumber());
            vector.add(staff.getUid());
            tableData.add(vector);
        }
        tableModel.fireTableDataChanged();
    }
}
